// 订单管理 云对象 111111111111111

const db = uniCloud.database();
const uniPayCo = uniCloud.importObject('uni-pay-co');
module.exports = {
	/**
	 * 创建新订单
	 * @param {Object} orderData - 订单数据
	 * @returns {Promise<Object>} 创建的订单信息
	 */
	async createOrder(orderData) {
		// 验证必要的订单数据
		if (!orderData.userinfo || !orderData.userinfo._id) {
			throw new Error('用户信息不能为空');
		}
		if (!orderData.goods || orderData.goods.length === 0) {
			throw new Error('订单商品不能为空');
		}


		// 构建完整订单数据
		const order = {
			...orderData,
			postage: orderData.postage || 0,
			discount: orderData.discount || 0
		};


		// 计算支付金额
		if (!order.pay_total_price) {
			order.pay_total_price = order.total_price + order.postage - order.discount;
		}


		// 插入数据库
		// const res = await db.collection('order').add(order).then((data)=>{
		await db.collection('order').add(order).then((data) => {
			return data;
		}).catch((err) => {
			return err
		});

		// 返回创建的订单信息
		// return {
		// 	res: {...res}
		// };
	},

	/**
	 * 获取订单详情
	 * @param {String} orderId - 订单ID或订单号
	 * @returns {Promise<Object>} 订单详情
	 */
	async getOrderDetail(orderId) {
		if (!orderId) {
			throw new Error('订单ID不能为空');
		}

		let order;

		// 尝试通过ID查询
		order = await db.collection('order').doc(orderId).get();

		// 如果没找到，尝试通过订单号查询
		if (!order.data || order.data.length === 0) {
			const res = await db.collection('order')
				.where({
					order_no: orderId
				})
				.get();
			order = res.data.length > 0 ? res.data[0] : null;
		} else {
			order = order.data[0];
		}

		if (!order) {
			throw new Error('未找到该订单');
		}

		return order;
	},

	/**
	 * 查询订单列表
	 * @param {Object} params - 查询参数
	 * @param {String} params.uid - 用户ID
	 * @param {Number} params.status - 订单状态
	 * @param {Number} params.page - 页码，默认1
	 * @param {Number} params.pageSize - 每页数量，默认10
	 * @returns {Promise<Object>} 订单列表及分页信息
	 */
	async getOrderList(uid, params = {}) {
		const {
			status_code,
			page = 1,
			pageSize = 10,
			searchVal
		} = params;
		let where;

		let query = db.collection('order');

		// 构建查询条件
		if (uid) {
			where = {
				'userinfo._id': uid
			}
		}

		if (status_code !== undefined) {
			// 状态查询，取最新的状态
			where = {
				'userinfo._id': uid,
				status_code: status_code
			};
		}
		if (searchVal && searchVal !== '') {
			// 状态查询，取最新的状态

			where = {
				'userinfo._id': uid,
				status_code: status_code,
				$or: [{
						'goods.cartList.goods_title': {
							$regex: searchVal,
							$options: 'i'
						}
					},
					{
						order_no: {
							$regex: searchVal,
							$options: 'i'
						}
					}
				]
			};

		}
		// 分页查询
		const skip = (page - 1) * pageSize;
		const orders = await query
			.where(where)
			.orderBy('create_date', 'desc')
			.skip(skip)
			.limit(pageSize)
			.get({
				getCount: true
			});
		const total = orders.affectedDocs
		return {
			list: orders.data,
			pagination: {
				page,
				pageSize,
				total: total,
				pages: Math.ceil(total / pageSize)
			}
		};
	},

	/**
	 * 更新订单信息
	 * @param {String} orderId - 订单ID
	 * @param {Object} updateData - 要更新的数据
	 * @returns {Promise<Object>} 更新结果
	 */
	async updateOrder(orderId, updateData) {
		if (!orderId) {
			throw new Error('订单ID不能为空');
		}

		if (Object.keys(updateData).length === 0) {
			throw new Error('更新数据不能为空');
		}

		// 处理订单状态更新
		if (updateData.status) {
			// 如果是新状态，添加到状态数组中
			if (updateData.status.code !== undefined) {
				const command = db.command;

				updateData.status_code = updateData.status.code
				// 添加新状态到数组
				updateData.status = command.push({
					...updateData.status,
					create_date: new Date()
				});
			}
		}

		// 处理支付状态更新
		if (updateData.is_pay === 1 && !updateData.pay_order_no) {
			throw new Error('支付成功时必须提供支付订单号');
		}

		// 执行更新
		const res = await db.collection('order')
			.where({
				order_no: orderId
			})
			.update(updateData);

		// if (res.updated === 0) {
		// 	throw new Error('更新订单失败，可能订单不存在或数据未变更');
		// }

		return {
			success: true,
			updated: res.updated
		};
	},
	
	//取消订单逻辑
	async cancelOrder(orderNo,text){
		if(!orderNo){
			throw new Error('订单ID不能为空');
		}
		var currentTime = new Date().getTime();
		//查询出当前订单的状态
		var order = await db.collection('order').where({order_no:orderNo}).get();
		var orderObject = order.data[0];
		//如果当前用户未支付，则直接更新订单状态，无需退款
		if(orderObject.is_pay == 0){
			var result = await db.collection('order').where({order_no:orderNo}).update({
				status:db.command.push({
					code:6,
					text:'已取消',
					desc:text,
					create_date:new Date().getTime()
				}),
				status_code:6
			});
			
			if(result.updated == 1){
				return {
					code:201,
					message:'未支付，已自动取消订单',
					result:result
				}
			}else{
				return {
					code:401,
					message:'订单取消失败',
					result:result
				}
			}
			
		}else if(orderObject.is_pay == 1){
			//再次验证支付状态
			var uniPayOrder = await db.collection('uni-pay-orders').where({order_no:orderNo}).get();
			var status = uniPayOrder.data[0].status;
			var out_trade_no = uniPayOrder.data[0].out_trade_no;
			if(status == 1){ //如果支付表里的状态也等于1，确定该订单确实真实支付了，这时候可以发起退款了。
				//判断下单时间是否超过了两小时，如果超过了则进入客服审核流程
				var payTime = orderObject.status[orderObject.status.findIndex((item)=>{
					return item.code == 1;
				})].create_date;
				
				if(currentTime - payTime > 3600000 * 2){
					var result = await db.collection('order').where({order_no:orderNo}).update({
						status:db.command.push({
							code:8,
							text:'退款审核中',
							desc:text,
							create_date:new Date().getTime()
						}),
						status_code:8
					});
					if(result.updated == 1){
						return {
							code:202,
							message:'已提交退款申请，客服审核中',
							result:result
						}
					}else{
						return {
							code:402,
							message:'退款申请提交失败',
							result:result
						}
					}
					
					
				}else{
					//查询出支付订单号
					var result = await db.collection('order').where({order_no:orderNo}).update({
						status:db.command.push({
							code:8,
							text:'退款审核中',
							desc:text,
							create_date:new Date().getTime()
						}),
						status_code:8
					});
					if(result.updated == 1){
						//发起退款
						const refund = await uniPayCo.refund({
						  out_trade_no: out_trade_no, // 插件支付单号
						  out_refund_no: 'refund_'+out_trade_no,
						  refund_desc: "用户主动申请退款"
						});
						
						if(refund.errCode == 0 && refund.errMsg == 'ok'){
							var result = await db.collection('order').where({order_no:orderNo}).update({
								status_code:5,
								status:db.command.push({
									code:5,
									desc:text,
									text:'已退款',
									create_date:new Date().getTime()
								})
							});
							if(result.updated == 1){
								return {
									code:203,
									message:'退款成功',
									result:refund
								}
							}				
						}
						
					}else{
						return {
							code:403,
							message:'系统自动退款发起失败',
							result:result
						}
					}
					
					
				}
			}
		}
	},
	
	/**
	 * 发起退款方法
	 */
	
	async refundOrder(orderNo){
		if(!orderNo){
			throw new Error('订单ID不能为空');
		}
		var uniPayOrder = await db.collection('uni-pay-orders').where({order_no:orderNo}).get();
		var status = uniPayOrder.data[0].status;
		var out_trade_no = uniPayOrder.data[0].out_trade_no;
		if(status == 1){
			//发起退款
			const refund = await uniPayCo.refund({
			  out_trade_no: out_trade_no, // 插件支付单号
			  out_refund_no: 'refund_'+out_trade_no,
			  refund_desc: "客服审核退款"
			});
			
			if(refund.errCode == 0 && refund.errMsg == 'ok'){
				var result = await db.collection('order').where({order_no:orderNo}).update({
					status_code:5,
					status:db.command.push({
						code:5,
						desc:'客服已退款',
						text:'已退款',
						create_date:new Date().getTime()
					})
				});
				if(result.updated == 1){
					return {
						code:203,
						message:'退款成功',
						result:refund
					}
				}				
			}
		}
	},
	
	/**
	 * 删除订单
	 * @param {String} orderId - 订单ID
	 * @returns {Promise<Object>} 删除结果
	 */
	async deleteOrder(orderId) {
		if (!orderId) {
			throw new Error('订单ID不能为空');
		}

		// 检查订单是否存在
		const order = await db.collection('order').doc(orderId).get();
		if (!order) {
			throw new Error('订单不存在');
		}

		// 检查订单状态，已支付的订单不允许删除
		const lastStatus = order.status[order.status.length - 1];
		if (lastStatus.code > 0) {
			throw new Error('已支付或已处理的订单不允许删除');
		}

		// 执行删除
		const res = await db.collection('order')
			.doc(orderId)
			.remove();

		return {
			success: true,
			deleted: res.deleted
		};
	},

	/**
	 * 订单支付操作
	 * @param {String} orderId - 订单ID
	 * @param {String} payOrderNo - 支付订单号
	 * @returns {Promise<Object>} 支付结果
	 */
	async payOrder(orderId, payOrderNo) {
		if (!orderId || !payOrderNo) {
			throw new Error('订单ID和支付订单号不能为空');
		}

		// 检查订单当前状态
		const order = await db.collection('order').doc(orderId).get();
		if (order.is_pay === 1) {
			throw new Error('该订单已支付');
		}

		// 更新订单状态为已支付
		return this.updateOrder(orderId, {
			is_pay: 1,
			pay_order_no: payOrderNo,
			status: {
				code: 1,
				text: '待发货'
			}
		});
	},

	/**
	 * 订单发货操作
	 * @param {String} orderId - 订单ID
	 * @param {Object} deliveryInfo - 物流信息
	 * @returns {Promise<Object>} 操作结果
	 */
	async shipOrder(orderId, deliveryInfo) {
		if (!orderId || !deliveryInfo || !deliveryInfo.title || !deliveryInfo.number) {
			throw new Error('订单ID和物流信息（公司和单号）不能为空');
		}

		// 检查订单当前状态
		const order = await db.collection('order').doc(orderId).get();
		const lastStatus = order.status[order.status.length - 1];
		if (lastStatus.code < 1) {
			throw new Error('只有已支付的订单才能发货');
		}
		if (lastStatus.code >= 2) {
			throw new Error('该订单已发货');
		}

		// 更新订单状态为已发货
		return this.updateOrder(orderId, {
			delivery: {
				...deliveryInfo,
				create_date: new Date()
			},
			status: {
				code: 2,
				text: '待收货'
			}
		});
	},
	
	/**
	 * 作用：获取订单支付状态
	 * @param {string} orderNo 订单号
	 * @return {object} 查询订单结果
	 */
	async getPayOrderStatus(orderNo){
		var res = await db.collection('uni-pay-orders').where({order_no:orderNo}).get();
		return {
			code:200,
			message:'请求成功',
			result:res
		}
	},
	
	/**
	 * 根据订单号更新订单表定单状态
	 * 
	 */
	async checkOrderStatus(order_no){
		var cmd = db.command;
		//查询出订单状态
		var uniPayOrder = await db.collection('uni-pay-orders').where({order_no:order_no}).get();
		var order = uniPayOrder.data[0];
		var totalFee = order.total_fee;
		var status = order.status;
		var custom = order.custom;
		var provider = order.provider;
		var currentTime = new Date().getTime();
		if(status == 1){
			if(order.total_fee != parseInt(custom.pay_total_price * 100)){
				return {
					code:102,
					message:'支付金额与订单总金额不一致，下单失败',
					result:{
						pay_total_price:totalFee,
						order_total_price:parseInt(custom.pay_total_price * 100)
					}
				}
			}
			
			//更新到订单表
			var updateOrder = await db.collection('order').where({order_no:order_no}).update({
				is_pay:1,
				status_code:1,
				provider:provider=='wxpay'?'微信支付':'支付宝支付',
				status:cmd.push({
					code:1,
					text:'待发货',
					create_date:currentTime
				})
			});
			
			return {
				code:200,
				message:'下单成功',
				result:updateOrder
			}
		}
		
	}
	
};